package com.erp.filter;

import java.io.IOException;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.erp.Resource.Resouce;



public class ReUrl implements Filter {

	public void destroy() {
	}
	/**
	 * 根据地址美化URL地址
	 */
	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = ((HttpServletResponse) res);
		String url = "";
		url = request.getRequestURI().replaceAll(request.getContextPath(), "");
		HashMap<UrlFilter, UrlFilter> map = Resouce.urlMap;
		UrlFilter filter = new UrlFilter(url);
		if (map.containsKey(filter)) {
			UrlFilter filter1 = map.get(filter);
			if (filter1.getRequest() == null) {

			} else {
				if (filter1.getRequest().equals("true")) { //替换url地址参数 根据正则表达式实现
					Pattern p = Pattern.compile(filter1.getGz());
					Matcher matcher = p.matcher(url);
					int count = matcher.groupCount();
					int index = 1;
					while (matcher.find(0)) {
						filter1.setUrl(filter1.getUrl().replace("$" + index,
								matcher.group(index)));
						index++;
						if (index > count) {
							break;
						}
					}
				}
			}
			if (filter1.getType() != null) {
				if (filter1.getType().equals("2")) {
					Resouce.clearParms(request);
				}
			}
			request.getRequestDispatcher("../" + filter1.getUrl()).forward(
					request, response);

		} else {
			chain.doFilter(request, response);
		}
	}

	public void init(FilterConfig arg0) throws ServletException {

		System.out.println(1);
	}

}
